package string_question.leecode.test22;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/6 19:56
 */
public class Solution1 {

    // 经典回溯算法
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) return res;
        helper(res, 0, 0, n, new StringBuilder());
        return res;
    }

    private void helper(List<String> res, int l, int r, int n, StringBuilder path) {
        if (l == n && r == n) {
            res.add(new String(path));
            return;
        }
        if (l > n || r > n || l < r) return;
        helper(res, l + 1, r, n, path.append("("));
        path.deleteCharAt(path.length() - 1);
        helper(res, l, r + 1, n, path.append(")"));
        path.deleteCharAt(path.length() - 1);
    }
}
